﻿angular.module('Stackoverflow').controller('QuestionDetailController', function ($scope, Restangular, $stateParams, $compile) {
    'use strict';

    if ($stateParams.id) {
        Restangular.one('question', $stateParams.id).get().then(function (model) {
            if (model) {
                $scope.model = {
                    title: model.title,
                    createdBy: model.userId,
                    answers: model.answers,
                    comments: model.comments,
                    content: model.content
                };
            }
        });

        $scope.answermodel = {
            answer: '',
            questionId: $stateParams.id,
            id: ''
        };

        $scope.commentmodel = {
            comment: '',
            parentId: $stateParams.id
        };

        $scope.saveAnswer = function (model) {
            return Restangular.all('answer').post($scope.answermodel).then(function (id) {
                if (id) {
                    var htmlcontent = $('.answer-content-container');
                    var item = $compile(' <div class="media answer-content"><div class="media-body">{{answermodel.answer}}</div></div>')($scope);
                    htmlcontent.append(item);
                }
            });
        };

        $scope.saveComment = function (model) {
            var htmlcontent = $('answer-comment-container');
            var item = $compile('<div>{{commentmodel.comment}}</div>')($scope);
            htmlcontent.append(item);

            return Restangular.all('comment').post($scope.commentmodel).then(function (id) {
                if (id) {
                    var htmlcontent = $('answer-comment-container');
                    var item = $compile('<div>{{commentmodel.comment}}</div>')($scope);
                    htmlcontent.append(item);
                }
            });
        };
    }
});